package com.cn.hz.zyj.controller;

import com.cn.hz.zyj.service.UserService;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jms.Queue;

@RestController
public class UserController {

    @Resource
    UserService userService;

    @Resource
    JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    Queue queue;

    @PostMapping("/user/add")
    public String addUser(@RequestParam("username") String username, @RequestParam("realname") String realname,
                          @RequestParam("pwd") String pwd, @RequestParam("student_id") String schoolId,
                          @RequestParam("userType") int userType){
        userService.addUser(username,realname,pwd,schoolId,userType);
        jmsMessagingTemplate.convertAndSend(queue," add new user successfully");
        return "success";
    }

    @GetMapping("/user/users")
    public String selectAll(){
        jmsMessagingTemplate.convertAndSend(queue," find all users "+userService.findAll());
        return "select success";
    }

    @PostMapping("/user/delete")
    public String deleteUser(@RequestParam("id") int userId){
        userService.deleteUser(userId);
        jmsMessagingTemplate.convertAndSend(queue,userId + " delete success");
        return "delete success";
    }

    @PostMapping("/user/select")
    public String selectUser(@RequestParam("userId") int id){
        jmsMessagingTemplate.convertAndSend(queue,"find user "+userService.findUser(id));
        return "select success";
    }

    @PostMapping("/user/login")
    public String login(@RequestParam("username") String username,@RequestParam("password") String password){
        jmsMessagingTemplate.convertAndSend(queue,username + " try to login");
        return userService.login(username,password) ? "login success" : "error password or username";
    }

    @PostMapping("/user/isLogin")
    public String isLogin(@RequestParam("username") String username){
        jmsMessagingTemplate.convertAndSend(queue,username + " try to test login");
        return userService.isLogin(username) ? username+" has login" : username+" logout";
    }
}
